<template>
  <el-card>
    <el-button type="warning" @click="handleCell">设置单元格样式</el-button>
    <el-table
      :data="tableData"
      style="width: 100%;border: none"
      border
      :cell-style="cellStyle"
      :header-cell-style="tableHeaderStyle"
      height="400"
      ref="multipleTable"
      @current-change="handleCurrentChange"
      @selection-change="handleSelectionChange"
      :default-sort = "{prop: 'index', order: 'descending'}"
      show-summary
      :summary-method="getSummaries"
      @sort-change="changeSort"
    >
<!--      :span-method="objectSpanMethod"
 :span-method="arraySpanMethod"-->

      <el-table-column
        type="selection"
      >
      </el-table-column>
<!--      label="索引"-->
<!--      type="index"-->
<!--      :index="indexMethod"-->
      <el-table-column
        label="索引"
        prop="name"
        :render-header="renderHeader"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="number"
        label="数字"
        width="80"
      >
      </el-table-column>
      <el-table-column
        prop="name"
        label="姓名"
        width="80"
        sortable
      >
      </el-table-column>
      <el-table-column
        prop="date"
        label="日期"
        width="180"
        sortable
      >
      </el-table-column>
      <el-table-column
        prop="address"
        label="地址"
      >
      </el-table-column>
      <el-table-column
        prop="numput"
        label="数字输入框"
      >
        <template slot-scope="scope">
          <el-input v-model="scope.row.numput" @change="getChange(scope.row)"></el-input>
        </template>

      </el-table-column>
<!--      <el-table-column>-->
<!--        <template slot="header" slot-scope="scope">-->
<!--          <el-input-->
<!--            v-model="search"-->
<!--            size="mini"-->
<!--            placeholder="输入关键字搜索"/>-->
<!--        </template>-->

<!--      </el-table-column>-->
      <el-table-column
        label="操作"
        fixed="right"
        width="200"
      >
        <template slot-scope="scope">
          <el-button type="primary" @click="handleEdit(scope)" size="mini" >修改</el-button>
          <el-button type="danger" @click="handleDelete(scope)" size="mini" >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 20px">
      <el-button @click="setCurrent(tableData[0])">选中第一行</el-button>
      <el-button @click="setCurrent()">取消选择</el-button>
    </div>
    <div style="margin-top: 20px">
      <el-button @click="toggleSelection([tableData[1], tableData[2]])">切换第二、第三行的选中状态</el-button>
      <el-button @click="toggleSelection()">取消选择</el-button>
    </div>
  </el-card>
</template>

<script>
export default {
name: "tablepage",
  data(){
    return {
      tableData: [{
        date: '2016-05-02',
        name: '王小虎',
        number:'1',
        address: '上海市普陀区金沙江路 1518 弄',
        numput:''
      }, {
        date: '2016-05-04',
        name: '王小虎',
        number:'2',
        address: '上海市普陀区金沙江路 1517 弄',
        numput:''
      }, {
        date: '2016-05-01',
        name: '王小虎',
        number:'3',
        address: '上海市普陀区金沙江路 1519 弄',
        numput:''
      }, {
        date: '2016-05-01',
        name: '王小虎',
        number:'4',
        address: '上海市普陀区金沙江路 1519 弄',
        numput:''
      }, {
          date: '2016-05-01',
          name: '王小虎',
          number:'5',
          address: '上海市普陀区金沙江路 1519 弄',
        numput:''
        }, {
        date: '2016-05-03',
        name: '王小虎',
        number:'6',
        address: '上海市普陀区金沙江路 1516 弄',
        numput:''
      }],
      currentRow: null,
      multipleSelection: [],
      search:'',
      inputValue:''
    }
  },
  mounted(){
  // this.handleInput()
  },
  methods:{
  // handleInput(){
  //   let inputDom = document.getElementById('inputDom');
  //   let maxLen = 0;
  //   inputDom.oninput = function() {
  //     let value = this.value;
  //     let valueLen = value.length;
  //     let foucsNum = getCursortPosition(inputDom);
  //     if(valueLen > 0){
  //       let c = value.replace(/\s/g,  "");
  //       let Len = c.length;
  //       let List = c.split('');
  //       let initNum = 0;
  //       for(let i=1;i<Len;i++) {
  //         if(i%4 == 0) {　　//每四位分一组
  //           List.splice(i+initNum,0,' ');　　//此处为使用空格分隔
  //           initNum++
  //         }
  //       }
  //       this.value  = List.join('');
  //
  //       if(maxLen < this.value.length) {
  //         if(foucsNum%5 == 0) {
  //           setTimeout(function() {
  //             setCaretPosition(inputDom,foucsNum+1)
  //           },0);
  //         }else {
  //           setTimeout(function() {
  //             setCaretPosition(inputDom,foucsNum)
  //           },0);
  //         }
  //       }else {
  //         if(foucsNum%5 == 0) {
  //           setTimeout(function() {
  //             setCaretPosition(inputDom,foucsNum-1)
  //           },0);
  //         }else {
  //           setTimeout(function() {
  //             setCaretPosition(inputDom,foucsNum)
  //           },0);
  //         }
  //       }
  //       maxLen = this.value.length;
  //     }
  //   }
  //   //控制光标移动时，需要使用定时器，避免出现光标控制失效的情况
  //   function getCursortPosition(ctrl) {        //获取光标的位置
  //     let CaretPos = 0;   // IE Support
  //     if (document.selection) {
  //       ctrl.focus();
  //       let Sel = document.selection.createRange();
  //       Sel.moveStart ('character', -ctrl.value.length);
  //       CaretPos = Sel.text.length;
  //     }
  //     // Firefox support
  //     else if (ctrl.selectionStart || ctrl.selectionStart == '0')
  //       CaretPos = ctrl.selectionStart;
  //     return (CaretPos);
  //   }
  //
  //   function setCaretPosition(ctrl, pos) {        //设置光标的位置
  //     if(ctrl.setSelectionRange){
  //       ctrl.focus();
  //       ctrl.setSelectionRange(pos,pos);
  //     }
  //     else if (ctrl.createTextRange) {
  //       let range = ctrl.createTextRange();
  //       range.collapse(true);
  //       range.moveEnd('character', pos);
  //       range.moveStart('character', pos);
  //       range.select();
  //     }
  //   }
  // },

    changeSort (val) {
      console.log(val) // column: {…} order: "ascending" prop: "date"
      // 根据当前排序重新获取后台数据,一般后台会需要一个排序的参数

    },
    renderHeader (h, column) {
      return h('div', [
          h('span', [
            h('span', {}, '姓名'),
            h('i',{class :'el-icon-d-caret',
              style: `cursor: pointer;`,
              on:{
                click: this.seeDetail
              }},''
            )
            ]
          )
        ]
      )
    },
    seeDetail() {
      console.log('查看详情111')
    },
    getChange(value){
      let length = this.tableData.length
      for(let i = 0;i<length;i++){
        if(this.tableData[i].number == value.number){
          let num = this.tableData[i].numput
          // 只能输入数字(/[^\d.]/g,"")
          num = num.replace(/[^\d^\.]+/g,'')
          //保留小数点后两位
          // num = num.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');
          //判断，如果输入的不是数字，赋值0
          if(!num){
            num = 0
          }
          console.log(num)
          //把数字转换为科学计数法 千分位格式化
          //.toFixed(2)保留小数点后两位
          //parseInt()只保留整数
          num = (parseFloat(num).toFixed(2) + '').replace(/\B(?=(?:\d{3})+\b)/g, ',')
          value.numput = num
        }
      }
      // // 只能输入数字
      // this.inputValue = value.replace(/[^\d^\.]+/g,'')
      // //保留小数点后两位
      // this.inputValue = this.inputValue.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');
      // //把数字转换为科学计数法
      // this.inputValue = (parseFloat(this.inputValue).toFixed(2) + '').replace(/\B(?=(?:\d{3})+\b)/g, ',')
    },
    //表头样式
    tableHeaderStyle({row, column, rowIndex, columnIndex}) {
      if (rowIndex === 0) {
        return 'background-color: gray; color:white;text-align:center;'
      }else {
        return ''
      }
    },
    //单元格样式
    cellStyle(row, column, rowIndex, columnIndex){
      console.log(rowIndex)
      if (row.rowIndex !== 0) {
          return 'background-color: purple; color:white;text-align:center;';
      }else if(row.rowIndex == 2) {
        console.log(row)
        return 'color:red'
      }else {
        return ''
      }
    },
    //修改
    handleEdit(scope){
      console.log("edit",scope.row,scope.$index)
    },
    //删除
    handleDelete(scope){
      console.log("delete",scope.row)
    },
    //当前选中行，当表格的当前行发生变化的时候会触发该事件
    handleCurrentChange(val) {
      this.currentRow = val
    },
    //选中某一行
    setCurrent(row){
      this.$refs.singleTable.setCurrentRow(row);
    },
    //多选
    handleSelectionChange(val) {
      this.multipleSelection = val
      console.log("多选",this.multipleSelection)
    },
    //切换选中行状态
    toggleSelection(rows){
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
    },
    //数字合计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总价';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += ' 元';
        } else {
          sums[index] = 'N/A';
        }
      });
      return sums;
    },
    // arraySpanMethod({ row, column, rowIndex, columnIndex }) {
    //   if (rowIndex % 2 === 0) {
    //     if (columnIndex === 0) {
    //       return [1, 2];
    //     } else if (columnIndex === 1) {
    //       return [0, 0];
    //     }
    //   }
    // },
    // objectSpanMethod({ row, column, rowIndex, columnIndex }) {
    //   if (columnIndex === 0) {
    //     if (rowIndex % 2 === 0) {
    //       return {
    //         rowspan: 2,
    //         colspan: 2
    //       };
    //
    //     } else {
    //       return {
    //         rowspan: 2,
    //         colspan: 0
    //       };
    //     }
    //
    //   }
    // },
    //索引值
    indexMethod(index){
      // return index * 2;
      return index
    },
    //页面跳转
    handleCell() {
      this.$router.push('/cell')
    },
  }
}
</script>

<style scoped>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>
